﻿// AGameServersManager.cs is part of AGatherBot.
//
// AGameServersManager is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as
// published by the Free Software Foundation.
//
// AGatherBot is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public version 2 License for more details.
//
// You should have received a copy of the GNU General Public License
// along with AGatherBot. If not, see <http://www.gnu.org/licenses/>.

using System;
using System.ComponentModel.Composition;
using System.Net;
using AGatherBot;
using AServerQuery;

namespace AGameServer
{
    public class AGameServersManager : IGameServersManager, IDisposable
    {
        #region Events

        public event Action<string, string> OnText = delegate { };
        public event Action<string> OnJoin = delegate { };

        #endregion

        #region Properties

        public LogListener Listener
        {
            get;
            private set;
        }

        #endregion

        #region Constructors

        public AGameServersManager()
        {
            this.Listener = new LogListener();

            foreach (var s in Properties.Settings.Default.GameServers)
            {
                var server = ParseGameServer(s);
                //this.Listener.AddServer(server);
            }
        }

        #endregion

        #region Methods

        private GoldSrc ParseGameServer(string value)
        {
            return null;
        }

        public void Connect()
        {
            // TODO: Check if it's listening?
            var interfaceIp = IPAddress.Parse(Properties.Settings.Default.InterfaceIP);
            var localEP = new IPEndPoint(interfaceIp, Properties.Settings.Default.ListeningPort);

            this.Listener.Listen(localEP);

            foreach (var server in this.Listener.Servers)
            {
                //server.AddLogAddress(
            }
        }

        public void Disconnect()
        {
            this.Listener.Stop();
        }

        public void Dispose()
        {
            this.Disconnect();
            // TODO: Dispose the gameservers ?
        }

        public void AddServer(IGameServer server)
        {
            var newServer = new GoldSrc(server.Address, server.RconPassword);
            this.Listener.AddServer(newServer);

            // If it is logging, listen to it?
        }

        public void RemoveServer(IGameServer server)
        {
            this.Listener.RemoveServer(server.Address);

            // If it's not logging, listen to it?
        }

        #endregion
    }
}